package graph;

import java.util.Arrays;

public class GraphByMatrix {
    int[][] matrix;//矩阵
    char[] arrayV;//顶点数组
    boolean isDirect;//是否为有向图
    public GraphByMatrix(int size,boolean isDirect) {
        arrayV=new char[size];
        matrix=new int[size][size];
        for (int i = 0; i < size; i++) {
            Arrays.fill(matrix[i],Constant.MAX);
        }
        this.isDirect=isDirect;
    }

    /**
     * 初始化顶点数组
     * @param array
     */
    public void initArrayV(char[] array) {
        for (int i = 0; i < array.length; i++) {
            arrayV[i]=array[i];
        }
    }

    /**
     * 添加边
     * @param srcV 起点
     * @param destV 终点
     * @param weight 权值
     */
    public void addEdge (char srcV,char destV,int weight) {
        int srcIndex=getIndexOfV(srcV);
        int destIndex=getIndexOfV(destV);
        matrix[srcIndex][destIndex]=weight;
        //如果是无向图
        if(!isDirect) {
            matrix[destIndex][srcIndex]=weight;
        }
    }

    /**
     * 获取顶点的度
     * @param v
     * @return
     */
    public int getDevOfV(char v) {
        int index=getIndexOfV(v);
        int count=0;
        for(int i=0;i<arrayV.length;i++) {
            if(matrix[index][i]!=Constant.MAX) {
                count++;
            }
        }
        //计算有向图的度
        if(isDirect) {
            for (int i = 0; i < arrayV.length; i++) {
                if(matrix[i][index]!=Constant.MAX) {
                    count++;
                }
            }
        }
        return count;
    }
    /**
     * 获取数组下标
     * @param src
     * @return
     */
    private int getIndexOfV(char src) {
        for (int i = 0; i < arrayV.length; i++) {
            if(arrayV[i]==src) {
                return i;
            }
        }
        return -1;
    }

}
